const { Service } = require('egg');
const { tableToList } = require('../utils/tools');

/**
 * 根据入学年份、开设学期（1、2、3、...）获取学期
 * @param {number} year 年份
 * @param {number} sub 开设学期（1、2、3、...）
 * @return {string} 学期
 */
const getTerm = (year, sub) => {
  const t1 = Number(year) + Math.floor((Number(sub) - 1) / 2);
  const t2 = Number(year) + Math.floor((Number(sub) - 1) / 2) + 1;
  return `${t1}-${t2}-${Number(sub) % 2 === 0 ? '2' : '1'}`;
};

module.exports = class PlanService extends Service {
  /**
   * 培养计划
   * @return {Array} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie;

    /* 再从培养方案明细中获取每个课程的开设学期，填补执行计划空缺 */
    const apiUrl1 = `${this.ctx.state.baseUrl}/jsxsd/pyfa/pyfa_query`;
    const p1 = this.ctx.curl(apiUrl1, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    });
    /* 从执行计划中获取每个课程的开设情况，但无开设学期 */
    const apiUrl2 = `${this.ctx.state.baseUrl}/jsxsd/pyfa/topyfamx`;
    const p2 = this.ctx.curl(apiUrl2, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    });
    const header = [ '课程名称', '属性', '性质', '学分', '考核方式', '学时', '开课院系' ]; // 列名称
    const columnNeed = [ 3, 8, -1, 5, 7, 6, 4 ]; // 需要提取的列序号
    const [ res1, res2 ] = await Promise.all([ p1, p2 ]);

    if (res1.status === 200 && res2.status === 200) {
      try {
        /* 因为培养计划中没有课程性质、学期，因此在修读情况页中获取数据并构造一个课程编号-类型的字典 */
        const tableList2 = tableToList(res2.data.toString(), '#mxh');
        const idDict = {};
        let type = '';
        tableList2.forEach((item, idx) => {
          if (idx < 2 || item[0] === '合计') return true;

          if (item[0] === '小计') {
            type = '';
            return true;
          }

          if (type === '') type = item[0];
          idDict[item[2]] = [ type, getTerm(this.ctx.data.sid.slice(0, 4), Number(item[item.length - 1])) ];

        });
        // console.log('idDict', idDict);
        /* end */

        const tableList1 = tableToList(res1.data.toString(), '#dataList');
        /* [ '序号', '开课学期', '课程编号', '课程名称', '开课单位', '学分', '总学时', '考核方式', '课程属性', '是否考试' ]; */
        // console.log('idDict', idDict);
        const info = {};
        for (let i = 1; i < tableList1.length; i++) {
          // if (!idDict[tableList1[i][2]]) console.log('tableList1[i]', tableList1[i].slice(0, 4));
          const term = idDict[tableList1[i][2]] ? idDict[tableList1[i][2]][1] : tableList1[i][1];
          if ((term in info) === false) { info[term] = []; }
          const tem = [];
          columnNeed.forEach(idx => {
            const type = idDict[tableList1[i][2]] ? idDict[tableList1[i][2]][0] : '';
            if (idx === -1) tem.push(type);
            else tem.push(tableList1[i][idx] || '');
          });
          info[term].push(tem);
        }
        return { table: info, header, status: true };

      } catch (err) {
        console.log('err', err);
        return err;
      }
    }
    return { table: {}, header, status: false };
  }

};
